package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hangzhou.xyj.R;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.UpdateCertificationHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.http.okhttp.OkHttpClientManager;
import com.hangzhou.xyj.net.request.UpdateCertificationReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.listener.CheckLoginListener;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.multiimageselector.MultiImageSelectorActivity;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.API;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Request;

/**
 * Created by Administrator on 2016/1/13.
 */
public class MyGroupAuthenActivity extends BaseActivity {
    public static final int REQUEST_CODE_IMAGE = 1;
    EditText mEtGroupName;//院团名称
    //    EditText mEtGroupCount;//团员数量
    EditText mEtGroupLeader;//团长
    //    EditText mEtGroupTelephone;//联系方式
    MyTextView mTvTip;//提示性文字
    MyImageView mIvImg;//占位图片
    CircleImageView mCivImg;//最后显示的图片
    RelativeLayout mLlContent;//图片区域
    RelativeLayout mRlChoose;//选择剧种区域
    MyTextView mTvCatType;//剧种名称
    EditText mEtIntroduce;//院团简介

    String mFilePath;//选择的图片的路径
    String mServerPath;//图片在服务器的路径
    String mGroupName;//院团名称
    String mCatId;//剧种的Id
    String mCatType;//剧种名称
    String mIntroduce;//简介
    String mGroupLeader;//团长
//    int mGroupMemberCount;//团员人数
//    String mContactPhone;//联系方式


    public boolean checkInput() {
        mGroupName = mEtGroupName.getText().toString().trim();//院团名称
        mGroupLeader = mEtGroupLeader.getText().toString().trim();//团长
//        mGroupMemberCount = Integer.valueOf(mEtGroupCount.getText().toString().trim());//团员人数
//        mContactPhone = mEtGroupTelephone.getText().toString().trim();//联系方式
        mIntroduce = mEtIntroduce.getText().toString().trim();//院团简介
        if (StringUtil.isEmpty(mGroupName)) {
            ToastUtil.show("院团名称不能为空");
            return false;
        }
        if (!PublicUtil.checkStrLength(mGroupName, 15)) {
            ToastUtil.show("院团名称不能超过15个字，请检查！");
            return false;
        }

        if (StringUtil.isEmpty(mCatType)) {
            ToastUtil.show("剧种不能为空");
            return false;
        }
        if (StringUtil.isEmpty(mGroupLeader)) {
            ToastUtil.show("团长不能为空");
            return false;
        }
        if (!PublicUtil.checkStrLength(mGroupLeader, 15)) {
            ToastUtil.show("团长不能超过15个字，请检查！");
            return false;
        }

        if (StringUtil.isEmpty(mIntroduce)) {
            ToastUtil.show("院团简介不能为空");
            return false;
        }
//
//        if (StringUtil.isEmpty(mContactPhone)) {
//            ToastUtil.show("联系方式不能为空");
//            return false;
//        }
//        if (!PublicUtil.isMobilePhone(mContactPhone)) {
//            ToastUtil.show("输入手机号不合法，请检查！");
//            return false;
//        }

        if (StringUtil.isEmpty(mFilePath)) {
            ToastUtil.show("请上传单位证明！");
            return false;
        }

        return true;
    }

    @Override
    public void initDatas() {
        registerEventBus();
    }

    /**
     * 选择圈子类别 事件订阅
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/22 10:08
     */
    @Subscribe
    public void onEventMainThread(CorrectRespEvent event) {
        switch (ECorrectType.valueOf(event.getTag())) {
            case CHOOSE:
                mCatType = event.getValue();
                mCatId = event.getValue2();
                mTvCatType.setText(mCatType);
                break;
        }
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_group_authen);
    }

    @Override
    public void initListeners() {
        mLlContent.setOnClickListener(new CheckLoginListener() {
            @Override
            public void onClickView(View v) {
                Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                IntentManager.getInstance().goImageSelectorActivity(MyGroupAuthenActivity.this, intent, REQUEST_CODE_IMAGE);
            }
        });

        mRlChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DramaCategoryListActivity.class);
                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_ADD_GROUP.getValue());
                intent.putExtra(DataKey.TITLE, "选择剧种");
                IntentManager.getInstance().goActivity(mContext, intent);
            }
        });
    }

    @Override
    public void initTop() {
        enableTitle(true, "认证");
        enableRightNav(true, "确定");
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                if (!checkInput()) {
                    return;
                }
                showLoadingDialog();
                //先上传图片
                uploadFile(mFilePath);
            }
        });
    }

    @Override
    public void initViews() {
        mEtIntroduce = findView(R.id.et_introduce);
        mTvCatType = findView(R.id.mtv_group_type);
        mRlChoose = findView(R.id.rl_choose);
//        mEtGroupCount = (EditText) findViewById(R.id.et_group_count);
        mEtGroupLeader = (EditText) findViewById(R.id.et_group_leader);
        mEtGroupName = (EditText) findViewById(R.id.et_group_name);
//        mEtGroupTelephone = (EditText) findViewById(R.id.et_group_telephone);
        mTvTip = findView(R.id.mtv_tip);
        mIvImg = findView(R.id.miv_image);
        mCivImg = findView(R.id.civ_img);
        mLlContent = findView(R.id.ll_content);
        //初始化光标位置到最后
        mEtGroupName.setSelection(mEtGroupName.length());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            mFilePath = path.get(0);
            mIvImg.setVisibility(View.GONE);
            mTvTip.setVisibility(View.GONE);
            ImageLoader.getInstance().displayImage("file:///" + mFilePath, mCivImg);
            mCivImg.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 单个文件上传
     *
     * @param
     * @return 返回上传到服务器以后，文件在服务器上的地址
     * @author yaohuix
     * @date 2016/3/18 13:38
     */
    public void uploadFile(String fileName) {
        try {
            OkHttpClientManager.getInstance().postAsyn(API.FILE_UPLOAD, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    ToastUtil.show("上传出错了!");
                }

                @Override
                public void onResponse(String response) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    boolean isSuccess = "success".equals(jsonObject.get("msg").getAsString()) ? true : false;
                    if (isSuccess) {
                        String path = jsonObject.get("data").getAsString();
                        mServerPath = path;
                        String groupName = mEtGroupName.getText().toString().trim();//院团名称
//                        String groupLeader = mEtGroupLeader.getText().toString().trim();//团长
//                        int groupMemberCount = Integer.valueOf(mEtGroupCount.getText().toString().trim());//团员人数
//                        String contactPhone = mEtGroupTelephone.getText().toString().trim();//联系方式
                        UpdateCertificationReq updateCertificationReq = new UpdateCertificationReq(Integer.valueOf(CommonPreferences.getUserId(mContext)),
                                mServerPath, groupName, mIntroduce, mCatId, mGroupLeader);
                        HttpLoader.getInstance().sendRequest(new UpdateCertificationHandler(updateCertificationReq, new MyHttpResponseListener() {
                            @Override
                            public void onSuccess(Object model) {
                                hideLoadingDialog();
                                ToastUtil.show("资料上传成功，请等待审核结果！");
                                CorrectRespEvent event = new CorrectRespEvent();
                                event.setTag(ECorrectType.AUTHEN.getValue());
                                EventBusUtil.postEvent(event);
                                closeActivity();
                            }
                        }, 0));
                    }
                }
            }, new File(fileName), "file");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
